<template>
  <div class="consult-page">
    <page-banner title="预约咨询" subtitle="专业顾问为您量身定制旅行方案" />

    <!-- 咨询表单 -->
    <div class="consult-form-section container">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="consult-form"
        :disabled="submitting"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入您的姓名" />
        </el-form-item>

        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入您的手机号码" />
        </el-form-item>

        <el-form-item label="预计出行时间" prop="travelDate">
          <el-date-picker
            v-model="form.travelDate"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled-date="disabledDate"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="出行人数" prop="peopleCount">
          <el-input-number
            v-model="form.peopleCount"
            :min="1"
            :max="20"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="意向目的地" prop="destinationId">
          <el-select
            v-model="form.destinationId"
            placeholder="请选择意向目的地"
            style="width: 100%"
          >
            <el-option
              v-for="item in destinations"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="特殊需求" prop="requirements">
          <el-input
            v-model="form.requirements"
            type="textarea"
            rows="4"
            placeholder="请描述您的特殊需求或疑问"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitting"
            >提交预约</el-button
          >
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 联系方式 -->
      <div class="contact-info">
        <h3>其他联系方式</h3>
        <p>
          <el-icon><Phone /></el-icon> 咨询电话：{{
            consultConfig.contactPhone || "028-12345678"
          }}
        </p>
        <p>
          <el-icon><ChatDotRound /></el-icon> 微信咨询：{{
            consultConfig.wechat || "travel_service"
          }}
        </p>
        <p v-if="consultConfig.email">
          <el-icon><Message /></el-icon> 邮箱：{{ consultConfig.email }}
        </p>
        <p v-if="consultConfig.workTime">
          <el-icon><Clock /></el-icon> 工作时间：{{ consultConfig.workTime }}
        </p>
      </div>
    </div>
  </div>
</template>

<script setup>
import PageBanner from "@/components/PageBanner.vue";
import { ref, onMounted, reactive } from "vue";
import { ElMessage } from "element-plus";
import { Phone, ChatDotRound, Message, Clock } from "@element-plus/icons-vue";
import {
  getConsultConfig,
  getConsultDestinations,
  submitConsult,
} from "@/api/consult";

const loading = ref(false);
const submitting = ref(false);
const destinations = ref([]);
const consultConfig = ref({});
const formRef = ref(null);

const form = reactive({
  name: "",
  phone: "",
  travelDate: null,
  peopleCount: 1,
  destinationId: "",
  requirements: "",
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入您的姓名", trigger: "blur" },
    { min: 2, max: 20, message: "姓名长度在 2 到 20 个字符", trigger: "blur" },
  ],
  phone: [
    { required: true, message: "请输入您的手机号码", trigger: "blur" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  travelDate: [
    { required: true, message: "请选择预计出行时间", trigger: "change" },
  ],
  destinationId: [
    { required: true, message: "请选择意向目的地", trigger: "change" },
  ],
};

// 禁用日期（今天之前的日期不可选）
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};

// 获取配置和目的地选项
const initData = async () => {
  loading.value = true;
  try {
    // 并行请求配置和目的地数据
    const [configRes, destRes] = await Promise.all([
      getConsultConfig(),
      getConsultDestinations(),
    ]);

    if (configRes) {
      consultConfig.value = configRes || {};
    }

    if (destRes) {
      destinations.value = destRes || [];
    }
  } catch (error) {
    console.error("初始化数据失败:", error);
    ElMessage.error("获取数据失败，请刷新页面重试");
  } finally {
    loading.value = false;
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning("请完善表单信息");
      return;
    }

    submitting.value = true;
    try {
      // 处理日期格式
      const submitData = {
        ...form,
        startDate: form.travelDate
          ? form.travelDate[0].toISOString().split("T")[0]
          : null,
        endDate: form.travelDate
          ? form.travelDate[1].toISOString().split("T")[0]
          : null,
      };

      delete submitData.travelDate;
      const res = await submitConsult(submitData);
      if (res) {
        ElMessage.success(res.msg || "预约提交成功，我们会尽快与您联系！");
        resetForm();
      } else {
        ElMessage.error(res.msg || "提交失败，请稍后重试");
      }
    } catch (error) {
      console.error("提交失败:", error);
      ElMessage.error("提交失败，请稍后重试");
    } finally {
      submitting.value = false;
    }
  });
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
    form.peopleCount = 1;
    form.travelDate = null;
  }
};

onMounted(() => {
  initData();
});
</script>

<style scoped>
.consult-page {
  background-color: var(--light-bg);
}

.consult-banner {
  height: 300px;
  margin-top: var(--header-height);
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
    linear-gradient(45deg, var(--primary-color), #36cfc9);
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  color: white;
}

.banner-content h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

.consult-form-section {
  padding: 60px 0;
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 40px;
}

.consult-form {
  background: white;
  padding: 40px;
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.contact-info {
  background: white;
  padding: 30px;
  border-radius: var(--border-radius);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.contact-info h3 {
  margin-bottom: 20px;
  color: var(--text-color);
}

.contact-info p {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  color: var(--text-color-secondary);
}

@media (max-width: 768px) {
  .consult-banner {
    height: 200px;
    margin-top: var(--header-height-mobile);
  }

  .banner-content h1 {
    font-size: 2rem;
  }

  .consult-form-section {
    grid-template-columns: 1fr;
    padding: 30px 15px;
  }

  .consult-form {
    padding: 20px;
  }
}
</style>
